package Watcher.video;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import com.sun.jna.NativeLibrary;

import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface;
import uk.co.caprica.vlcj.player.events.VideoOutputEventListener;

public class Player {

	private final JFrame frame;
	private final JPanel contentPane;
	private final Canvas canvas;

	private final MediaPlayerFactory mediaPlayerFactory;
	protected final EmbeddedMediaPlayer mediaPlayer;
	private final CanvasVideoSurface videoSurface;

	public static void start(final String link) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new Player().startVideo(link);
			}
		});
	}

	protected Player() {
		// TODO NativeLibrary-Pfad in Property-File auslagern
		NativeLibrary.addSearchPath("libvlc",
				"C:\\Program Files\\VideoLAN\\VLC");
		canvas = new Canvas();
		canvas.setBackground(Color.black);

		contentPane = new JPanel();
		contentPane.setBackground(Color.black);
		contentPane.setLayout(new BorderLayout());
		contentPane.add(canvas, BorderLayout.CENTER);

		frame = new JFrame("My vlcj player");
		frame.setContentPane(contentPane);
		frame.setSize(800, 600);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		mediaPlayerFactory = new MediaPlayerFactory(
				new String[] { "--no-video-title-show" });

		mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
		videoSurface = mediaPlayerFactory.newVideoSurface(canvas);

		mediaPlayer.setVideoSurface(videoSurface);

		mediaPlayer.addVideoOutputEventListener(new VideoOutputEventListener() {
			@Override
			public void videoOutputAvailable(MediaPlayer mediaPlayer,
					boolean videoOutput) {
				if (videoOutput) {
					Dimension size = mediaPlayer.getVideoDimension();
					if (size != null) {
						canvas.setSize(size.width, size.height);
						frame.pack();
					}
				}
			}
		});

		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				mediaPlayer.release();
				mediaPlayerFactory.release();
			}
		});

		frame.setVisible(true);
	}

	protected void startVideo(final String link) {
		mediaPlayer.playMedia(link);
	}
}